package com.ttxz.common

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import com.hjq.toast.ToastUtils
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.FormatStrategy
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import com.ttxz.common.constants.CommonConstant
import com.ttxz.common.crash.MyCrashHandler
import com.ttxz.common.crash.MyCrashListener
import com.ttxz.common.utils.log.LogUtil.d

/**
 * Application的基类
 *
 * @author ttxz
 * @date 2022/6/10 14:05
 */
abstract class BaseApplication : Application() {


    @SuppressLint("StaticFieldLeak")
    object Instance{
        lateinit var mApplication:BaseApplication
        lateinit var mContext: Context
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        Instance.mContext = base
        Instance.mApplication = this
    }

    override fun onCreate() {
        super.onCreate()
        initLogger()
        initToast()
        registerActivityLifecycleCallbacks(MyActivityLifecycleCallbacks())
        initCrash()
    }

    private fun initLogger() {
        val formatStrategy: FormatStrategy = PrettyFormatStrategy.newBuilder()
            .showThreadInfo(false) // 是否显示线程信息。默认显示
            .methodCount(0) // 要显示多少条方法行。默认 2
            .methodOffset(7) // 隐藏内部方法调用到偏移量。默认 5
            //                .logStrategy(customLog) // 更改日志策略以打印输出。默认 LogCat
            .tag(CommonConstant.LOG_TAG) // 每个日志的全局标签。默认 PRETTY_LOGGER
            .build()
        Logger.addLogAdapter(object : AndroidLogAdapter(formatStrategy) {
            override fun isLoggable(priority: Int, tag: String?): Boolean {
                return isLoggable
            }
        })
        d("日志模块初使化完成")
    }

    private fun initToast() {
        // 初始化 Toast 框架
        ToastUtils.init(this)
        //默认在屏幕中间显示
//        ToastUtils.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 100);
    }

    private fun initCrash() {
        MyCrashHandler().init(
            this, object : MyCrashListener {
                override fun onCrash(errorStr: String?, originalThrowable: Throwable?) {
                    onCrash(errorStr, originalThrowable)
                }
            }
        )
    }

    /**
     * 日志模块是否输出，建议使用 {BuildConfig.DEBUG}
     * @return 是否输出日志，`true` 则输出，反之，不输出
     */
    abstract val isLoggable: Boolean

    /**
     * 应用发生异常后的错误日志的处理
     * @param errorStr          转换成String类型的堆栈信息
     * @param originalThrowable 转换前的Throwable对象实例
     */
    abstract fun onCrash(errorStr: String?, originalThrowable: Throwable?)
}